package com.taxshare.manager.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.manager.constant.ResultConstant;
import com.taxshare.manager.entity.ResourceEntity;
import com.taxshare.manager.entity.RoleResourceEntity;
import com.taxshare.manager.mapper.RoleResourceMapper;
import com.taxshare.manager.view.dto.RoleResourceDTO;
import com.taxshare.manager.view.vo.ResourceVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: RoleResourceService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/1/28 10:43
 */
@Service
public class RoleResourceService extends ServiceImpl<RoleResourceMapper, RoleResourceEntity> {

    /**
     * 初始化资源树
     *
     * @return
     */
    public Response initResourceTree() {
        //获取当前用户类型
        String useType = UserInfoUtil.getUserType();
        List<ResourceEntity> resourceList = null;
        //普通用户，集团管理员，系统管理员获取对应的资源菜单
        if (CommonConstant.AUTH_TYPE_1.equals(useType) || CommonConstant.AUTH_TYPE_2.equals(useType)) {
            resourceList = baseMapper.queryResourceInfoByUserId(UserInfoUtil.getUserID());
        }/* else if (CommonConstant.AUTH_TYPE_2.equals(useType)) {
            resourceList = baseMapper.queryResourceInfo();
        }*/ else if (CommonConstant.AUTH_TYPE_3.equals(useType)) {
            resourceList = baseMapper.querySystemResourceInfo();
        }
        if (CollectionUtils.isEmpty(resourceList)) {
            return Response.success(resourceList);
        }
        List<ResourceVO> resourceVOList = JSONUtil.toList(JSONUtil.parseArray(resourceList), ResourceVO.class);
        //构造菜单树
        Map<String, ResourceVO> dataMap = new HashMap<>(resourceVOList.size() * 4 / 3 + 1);
        for (ResourceVO bean : resourceVOList) {
            dataMap.put(bean.getResourceId(), bean);
        }
        //构造Tree
        List<ResourceVO> treeList = new ArrayList<>(30);
        for (ResourceVO bean : resourceVOList) {
            //如果父节点为0,则表示其为根节点
            if ("0".equals(bean.getResourceParentId())) {
                treeList.add(bean);
            } else {
                //获取父节点所在的对象
                ResourceVO parentEntity = dataMap.get(bean.getResourceParentId());
                //如果为null则表明此节点的父节点不存在了
                if (parentEntity != null) {
                    //将其存放到父节点的children属性下
                    parentEntity.getChildren().add(bean);
                }
            }
        }
        return Response.success(treeList);
    }

    /**
     * 获取角色资源树
     *
     * @return
     */
    public Response getResourceTree(String roleId) {
        QueryWrapper<RoleResourceEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("t.role_id", roleId);
        List<String> resourceList = baseMapper.queryResourceInfoByRoleId(queryWrapper);
        return Response.success(resourceList);
    }

    /**
     * 保存角色资源树
     *
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public Response saveResource(RoleResourceDTO pojo) {
        if (ArrayUtil.hasEmpty(pojo.getResourceId())) {
            return Response.error(ResultConstant.RET_R0003_CODE, ResultConstant.RET_R0003_MSG);
        }
        if (StrUtil.hasBlank(pojo.getRoleId())) {
            return Response.error(ResultConstant.RET_R0004_CODE, ResultConstant.RET_R0004_MSG);
        }
        //删除该角色的资源信息
        Map<String, Object> delMap = new HashMap<>(8);
        delMap.put("role_id", pojo.getRoleId());
        this.removeByMap(delMap);
        //插入角色资源信息
        List<RoleResourceEntity> insertEntityList = new ArrayList<>();
        RoleResourceEntity entity;
        for (String resourceId : pojo.getResourceId()) {
            entity = new RoleResourceEntity();
            entity.setUuid(UUIDUitl.UUID32(false));
            entity.setRoleId(pojo.getRoleId());
            entity.setResourceId(resourceId);
            insertEntityList.add(entity);
        }
        this.saveBatch(insertEntityList);
        return Response.success();
    }
}
